package com.huanxun.foodspath3;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

import com.huanxun.bean.MsgDetailBean_Factory;
import com.huanxun.bean.MsgDetailBean_Factory.DataEntityFactory;
import com.huanxun.bean.MsgDetailBean_Factory.PurchaseProcessInfoList;
import com.huanxun.utils.Constants;
import com.huanxun.utils.MLogger;
import com.huanxun.utils.SystemUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.lidroid.xutils.view.annotation.ViewInject;

/**
 * 
 * 工厂 消息详情. 
 */
public class MsgDetail extends Activity implements OnClickListener {

	private MAdapter mAdapter;
	private M2Adapter m2Adapter;

	private ArrayList<String> strs;
	private ArrayList<String> strs2;
	private ArrayList<String> strs4;
	private ArrayList<String> strs5;
	private ArrayList<String> strs6;
	private ArrayList<String> strs7;
	private String id;
	private String title;
	private String time;

	@ViewInject(R.id.sv)
	private ScrollView sv;
	@ViewInject(R.id.lll)
	private LinearLayout lll;
	@ViewInject(R.id.ll_notify)
	private LinearLayout ll_notify;
	@ViewInject(R.id.line)
	private View line;
	@ViewInject(R.id.iv_msgdetail_back)
	private ImageView iv_msgdetail_back;
	@ViewInject(R.id.lv_content)
	private ListView lv_content;
	@ViewInject(R.id.tv_msgdetail_title)
	private TextView tv_msgdetail_title;
	@ViewInject(R.id.tv_date)
	private TextView tv_date;
	@ViewInject(R.id.lv_port)
	private ListView lv_port;
	@ViewInject(R.id.rl)
	private RelativeLayout rl;
	private List<com.huanxun.bean.MsgDetailBean_Factory.PortList> portInfoList;
	private String productNecessaryId;
	private List<PurchaseProcessInfoList> purchaseProcessInfoList;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_msgdetail);

		ViewUtils.inject(this);
		getData();
		LoadMsgListData();

	}

	private void LoadMsgListData() {
		String path = Constants.URL_MSG_DETAIL;
		MLogger.i("Url_Factory_Detail", path+id);
		SystemUtils.httpUtils.send(HttpMethod.GET, path + id,
				new RequestCallBack<String>() {

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						String result = responseInfo.result;
						
						MLogger.i("Factory_Detail", result);
						processData(result);
					}

					@Override
					public void onFailure(HttpException error, String msg) {
						MLogger.i("Factory_Detail", "failed");
						runOnUiAlert("网络错误");
					}
				});
	}

	protected void processData(String result) {

		MsgDetailBean_Factory msgDetailBean = SystemUtils.gson.fromJson(result,
				MsgDetailBean_Factory.class);
		if ("fail".equals(msgDetailBean.msg)) {
			SystemUtils.toast(getApplicationContext(), "数据加载失败");
			finish();
		} else {
			strs4 = new ArrayList<String>();
			strs5 = new ArrayList<String>();
			strs6 = new ArrayList<String>();
			strs7 = new ArrayList<String>();
			DataEntityFactory data = msgDetailBean.data;
			productNecessaryId = data.productNecessaryId;
			portInfoList = data.portInfoList;
			for (int i = 0; i < portInfoList.size(); i++) {
				com.huanxun.bean.MsgDetailBean_Factory.PortList portList0 = portInfoList
						.get(i);
				if (i == 0) {
					addPortName(strs4,portList0);
				} else if (i == 1) {
					addPortName(strs5,portList0);
				}else if (i == 2) {
					addPortName(strs6,portList0);
				}else {
					addPortName(strs7,portList0);
				}
			}
			purchaseProcessInfoList = data.purchaseProcessInfoList;
			for (int i = 0; i < purchaseProcessInfoList.size(); i++) {
				PurchaseProcessInfoList purchaseProcessInfoList2 = purchaseProcessInfoList
						.get(i);
				if (i == 0) {
					addProcess(strs4,purchaseProcessInfoList2);
				} else if(i == 1){
					addProcess(strs5,purchaseProcessInfoList2);
				}else if(i == 2){
					addProcess(strs6,purchaseProcessInfoList2);
				}else {
					addProcess(strs7,purchaseProcessInfoList2);
				}
			}
			long deliveryTime = data.deliveryTime;
			List<String> qualifications = data.qualifications;
			String changeTimeFormat = SystemUtils
					.changeTimeFormat(deliveryTime);

			strs = new ArrayList<String>();
			strs2 = new ArrayList<String>();
			strs.add("公司名称: ");
			strs2.add(data.companyName);
			strs.add("官方评价: ");
			strs2.add(data.evaluate);
			strs.add("用户好评: ");
			strs2.add(data.highOpinion);
			strs.add("产品大类: ");
			strs2.add(data.bigTypeName);
			strs.add("产品小类: ");
			strs2.add(data.middleTypeName);
			strs.add("产品名称: ");
			strs2.add(data.typeName);
			strs.add("发货时间: ");
			strs2.add(changeTimeFormat);
			strs.add("付款方式: ");
			strs2.add(data.paymentType);
			strs.add("运输方式: ");
			strs2.add(data.transportType);
			StringBuilder temp = new StringBuilder();
			for (int i = 0; i < qualifications.size(); i++) {
				String string = qualifications.get(i);
				if (qualifications.size() - 1 == i) {
					temp.append(string);
				} else {
					temp.append(string + " ; ");
				}
			}
			String qualification = temp.toString();
			strs.add("资质要求: ");
			if (TextUtils.isEmpty(qualification)) {
				strs2.add("无");
			} else {
				strs2.add(qualification);
			}

			initView();
		}

	}

	private void addProcess(ArrayList<String> strs42, PurchaseProcessInfoList purchaseProcessInfoList2) {
		String packageProcessName = purchaseProcessInfoList2.packageProcessName;
		String productProcessName = purchaseProcessInfoList2.productProcessName;
		String amount = purchaseProcessInfoList2.amount;
		strs42.add("数　　量:" + amount);
		strs42.add("包装工艺:" + packageProcessName);
		strs42.add("产品工艺:" + productProcessName);
	}

	private void addPortName(
			ArrayList<String> strs, com.huanxun.bean.MsgDetailBean_Factory.PortList portList) {
		strs.add("出货港" + ":" + portList.portName);
	}

	private void initView() {
		sv.smoothScrollTo(0, 0);
		rl.setVisibility(View.GONE);
		iv_msgdetail_back.setOnClickListener(this);
		tv_msgdetail_title.setText(title);
		tv_date.setText(time);

		interfaceDisplay();
		mAdapter = new MAdapter();
		lv_content.setAdapter(mAdapter);
		m2Adapter = new M2Adapter();
		lv_port.setAdapter(m2Adapter);
	}
	
	/*
	 * 其中包括发货港口相关信息  及  货物的报价.
	 */
	private class M2Adapter extends BaseAdapter {

		@Override
		public int getCount() {

			return portInfoList.size();
		}

		@Override
		public Object getItem(int position) {
			return null;
		}

		@Override
		public long getItemId(int position) {
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View view = View.inflate(MsgDetail.this, R.layout.item_iv_offer,
					null);
			final EditText et_offer2 = (EditText) view
					.findViewById(R.id.et_offer2);
			Button bt_offer2 = (Button) view.findViewById(R.id.bt_offer2);

			com.huanxun.bean.MsgDetailBean_Factory.PortList portList = portInfoList
					.get(position);
			final String portId = portList.portId;
			PurchaseProcessInfoList purchaseProcessInfoList2 = purchaseProcessInfoList
					.get(position);
			final String productProcessId = purchaseProcessInfoList2.productProcessId;
			et_offer2.setOnEditorActionListener(new OnEditorActionListener() {

				@Override
				public boolean onEditorAction(TextView v, int actionId,
						KeyEvent event) {
					if (actionId == EditorInfo.IME_ACTION_NEXT
							|| actionId == EditorInfo.IME_ACTION_DONE) {
						InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
						imm.hideSoftInputFromWindow(et_offer2.getWindowToken(),
								0);
					}

					return true; 
				}
			});
			
			/*工厂提交报价的按钮 点击事件*/
			bt_offer2.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					final String price = et_offer2.getText().toString();
					if(TextUtils.isEmpty(price)){
						SystemUtils.toast(MsgDetail.this, "报价不可为空!");
						return;
					}else if(Long.parseLong(price)<=0){
						SystemUtils.toast(MsgDetail.this, "报价不可为0!");
						return;
					}
					//判断隐藏软键盘是否弹出
					if (getWindow().getAttributes().softInputMode == WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED
							) {
					//隐藏软键盘	
						getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
						
					}
					et_offer2.setText("");
					new Thread() {
						public void run() {
							String urlPath  = "http://112.126.80.199:9990/foodspath/v02/order/factory/";
							URL url;
							JSONObject jsonObject = new JSONObject();
							JSONObject jsonObject2 = new JSONObject();
							JSONArray array = new JSONArray();
							try {
								url = new URL(urlPath);
								jsonObject.put("productNecessaryId",
										productNecessaryId);
								jsonObject2.put("processArrayId",
										productProcessId);
								jsonObject2.put("portId", portId);
								jsonObject2.put("quote", price);
								array.put(jsonObject2);
								jsonObject.put("factoryQuoteList", array);
								MLogger.i("Order_Factory", "productNecessaryId:"+productNecessaryId);
								MLogger.i("Order_Factory", "productProcessId:"+productProcessId);
								MLogger.i("Order_Factory", "portId:"+portId);
								MLogger.i("Order_Factory", "price:"+price);
								
								String content2 = jsonObject.toString();
								InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
								imm.hideSoftInputFromWindow(
										et_offer2.getWindowToken(), 0);

								HttpURLConnection conn = (HttpURLConnection) url
										.openConnection();
								conn.setConnectTimeout(5000);
								conn.setDoOutput(true);
								conn.setRequestMethod("POST");
								conn.setRequestProperty("ser-Agent", "Fiddler");
								conn.setRequestProperty("Content-Type",
										"application/json");
								OutputStream os = conn.getOutputStream();
								os.write(content2.getBytes());
								os.close();
								int code = conn.getResponseCode();
								MLogger.i("Code_Factory_response", code + "");
								if (code == 200) {
									runOnUiAlert("报价成功!");

									InputStream is = conn.getInputStream();
									String json = com.huanxun.engine.NetUtils
											.readBytes(is);

									MLogger.i("Server_response_Factory", json);
									JSONObject jsonObject3 = new JSONObject(
											json);
									String string = jsonObject3
											.getString("msg");
									MLogger.i("Server_response_Factory", string);
								} else {
									runOnUiAlert("报价失败!");
								}
							} catch (Exception e) {
								runOnUiAlert("请检查网络!");
								e.printStackTrace();
							}

						}

					}.start();
				}
			});

			ListView lv_product_info = (ListView) view
					.findViewById(R.id.lv_product_info);
			
			/*将此listView中的item的positon传递给下一个ListView*/
			M44Adapter m44Adapter = new M44Adapter(position);
			lv_product_info.setAdapter(m44Adapter);
			return view;
		}

	}

	static class ViewHolder2 {
		EditText et_offer2;
	}
	
	/*其中包括港口相关信息    不包括货物的报价*/
	private class M44Adapter extends BaseAdapter {
		/*获取上个ListView(M2Adapter)传递item的positon位置,根据此positon的值.来为新的LivewView(M44Adapter)
	    适配器Adapter确定匹配的数据源. 
	 */
		public int count;

		public M44Adapter(int position) {
			this.count = position;
		}

		@Override
		public int getCount() {
		if(count==0){
			return strs4.size();
		}else if(count==1){
			return strs5.size();
		}else if(count==2){
			return strs6.size();
		}else {
			return strs7.size();
		}
		}

		@Override
		public Object getItem(int position) {

			return null;
		}

		@Override
		public long getItemId(int position) {

			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View view = View.inflate(MsgDetail.this,
					R.layout.item_product_info, null);

			TextView tv_info = (TextView) view.findViewById(R.id.tv_info);
			String string = "";
			if(count==0){
				string=strs4.get(position);
			}else if(count==1){
				string=strs5.get(position);
			}else if(count==2){
				string=strs6.get(position);
			}else{
				string=strs7.get(position);
			}

			tv_info.setText(string);
			return view;
		}

	}

	private void interfaceDisplay() {
		Resources resources = getResources();
		Drawable drawable = resources.getDrawable(R.drawable.edit_text_bg2);
		lll.setBackgroundDrawable(drawable);
		ll_notify.setVisibility(View.VISIBLE);
		line.setVisibility(View.VISIBLE);
	}

	private class MAdapter extends BaseAdapter {

		@Override
		public int getCount() {

			return strs.size();
		}

		@Override
		public Object getItem(int position) {

			return strs.get(position);
		}

		@Override
		public long getItemId(int position) {

			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View view = null;
			ViewHolder holder = null;
			if (convertView == null) {
				view = View.inflate(MsgDetail.this, R.layout.item_msgdetail,
						null);
				holder = new ViewHolder();
				holder.tv_paragraph = (TextView) view
						.findViewById(R.id.tv_paragraph);
				holder.tv_paragraph2 = (TextView) view
						.findViewById(R.id.tv_paragraph2);
				view.setTag(holder);
			} else {
				view = convertView;
				holder = (ViewHolder) view.getTag();
			}

			String key1 = strs.get(position);
			String value1 = strs2.get(position);
			holder.tv_paragraph.setText(key1);
			holder.tv_paragraph2.setText(value1);

			return view;
		}

	}

	static class ViewHolder {
		TextView tv_paragraph;
		TextView tv_paragraph2;

	}

	private void getData() {
		Intent intent = getIntent();
		title = intent.getStringExtra("title");
		time = intent.getStringExtra("time");
		id = intent.getStringExtra("id");

	}

	@Override
	public void onClick(View v) {
		finish();
	}

	private void runOnUiAlert(final String text) {
		runOnUiThread(new Runnable() {

			@Override
			public void run() {
				Toast.makeText(MsgDetail.this, text, Toast.LENGTH_SHORT).show();
			}
		});
	};

}
